package cn.juque.workflow.helper;

import cn.juque.common.constants.MessageEnum;
import cn.juque.common.exception.AppException;
import cn.juque.workflow.api.enums.WorkflowMsgEnum;
import cn.juque.workflow.bo.TaskFinishParamBO;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.engine.task.Task;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>TaskInfoHelper</li>
 * </ul>
 * @date 2023-02-04 15:27:00
 **/
@Component("taskInfoHelper")
public class TaskInfoHelper {

    @Resource
    private TaskService taskService;

    @Resource
    private IdentityService identityService;

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private HistoryService historyService;

    /**
     * 获取任务
     *
     * @param taskId 任务ID
     * @return Task
     */
    public Task getById(String taskId) {
        return this.taskService.createTaskQuery().taskId(taskId).singleResult();
    }

    /**
     * 获取实例ID
     *
     * @param taskId 任务ID
     * @return string
     */
    public String getInstanceId(String taskId) {
        Task task = this.getById(taskId);
        if (null != task) {
            return task.getProcessInstanceId();
        }
        HistoricTaskInstance taskInstance = this.historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        if (null != taskInstance) {
            return taskInstance.getProcessInstanceId();
        }
        throw new AppException(MessageEnum.PARAM_ERROR.getCode(), "任务不存在");
    }

    /**
     * 完成任务
     *
     * @param paramBO 参数
     */
    public void taskFinish(TaskFinishParamBO paramBO) {
        Task task = this.taskService.createTaskQuery().taskId(paramBO.getTaskId()).singleResult();
        if (null == task) {
            throw new AppException(WorkflowMsgEnum.TASK_MISSING_OR_FINISH);
        }
        String processInstanceId = task.getProcessInstanceId();
        Map<String, Object> variableMap = paramBO.getVariableMap();
        this.identityService.setAuthenticatedUserId(paramBO.getTaskAssignee());
        this.taskService.createComment(task.getId(), processInstanceId, paramBO.getApproveRemark());
        this.taskService.complete(task.getId(), variableMap);
    }
}
